package cn.zzq.aix.nativeinterface.javareflector;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import com.google.appinventor.components.runtime.Form;
import com.google.appinventor.components.runtime.ReplForm;
import com.google.appinventor.components.runtime.util.YailList;

import android.os.Environment;
import dalvik.system.BaseDexClassLoader;
import gnu.lists.FString;
import gnu.math.Complex;

public class Util {
	public static boolean isAICompanion() {
		if (isAndroidEnvironment()) {
			return ReplForm.class.isInstance(Form.getActiveForm());
		}
		return false;
	}

	public static String parseAsAbsolutePath(String path) {
		String sdDir = null;
		String dataFileDir = null;
		if (isAndroidEnvironment()) {
			sdDir = Environment.getExternalStorageDirectory().getAbsolutePath();
			dataFileDir = Form.getActiveForm().getFilesDir().getAbsolutePath();
		} else {
			// java中运行时的测试的虚拟路径
			sdDir = "/storage/0/sdcard";
			dataFileDir = "/data/data/packageName/file";
		}
		if (path.startsWith("/sdcard")) {
			// 内存卡
			if (path.equals("/sdcard") || path.equals("/sdcard/")) {
				// sd卡根目录
				path = sdDir;
			} else {
				path = sdDir + path.substring(7);
			}
		} else if (path.startsWith("~/")) {
			path = dataFileDir + path.substring(1);
		} else if (path.startsWith("//")) {
			// 素材文件
			if (isAndroidEnvironment()) {
				if (isAICompanion()) {
					return parseAsAbsolutePath("/sdcard/AppInventor/assets" + path.substring(1));
				} else {
					throw new ReflectException(path, "Util.parseAsAbsolutePath", "在生成的apk文件中无法获取素材文件的文件的绝对路径", path);
				}
			} else {
				return parseAsAbsolutePath("/sdcard/AppInventor/assets" + path.substring(1));
			}
		} else if (!path.startsWith("/")) {
			throw new ReflectException(path, "Util.parseAsAbsolutePath", "不合法的文件路径");
		}
		try {
			return new File(path).getCanonicalPath();
		} catch (IOException e) {
			throw new ReflectException(path, "Util.parseAsAbsolutePath", e, "发生io异常");
		}
	}

	/**
	 * ai列表转换为类对象数组
	 * 
	 * @param classList
	 *            类对象列表
	 * @return 类对象数组
	 * 
	 * @throws ClassNotFoundException
	 *             若列表中存在类名形式的类，有可能找不到此类,则会触发此异常
	 */
	public static Class<?>[] list2Classes(YailList classList) throws ClassNotFoundException {
		Object[] classes = classList.toArray();
		Class<?>[] classes2 = new Class<?>[classes.length];
		for (int i = 0; i < classes.length; i++) {
			Object clazz = classes[i];
			if (clazz instanceof String || clazz instanceof FString) {
				classes2[i] = ClassManager.getClassManager().get(clazz.toString());
			} else {
				classes2[i] = (Class<?>) classes[i];
			}
		}
		return classes2;
	}

	/**
	 * 1.传入一个方法，将返回这个方法<br/>
	 * 2.传入一个字符串，将解析这个字符串
	 * 
	 * @param mn
	 * @return
	 */
	public static Method parseAsMethod(Object mn) {
		if (mn instanceof String || mn instanceof FString) {
			try {
				return TextReflectUtil.getMethodByPattern(mn.toString());
			} catch (Exception e) {
				// 可能找不到类或方法
				throw new ReflectException(mn, "parseAsMethod", e);
			}
		} else {
			return (Method) mn;
		}
	}

	public static boolean isAndroidEnvironment() {
		return Util.class.getClassLoader() instanceof BaseDexClassLoader;
	}

	public static Constructor<?> parseAsConstructor(Object cn) {
		if (cn instanceof String || cn instanceof FString) {
			try {
				return TextReflectUtil.getConstructorByPattern(cn.toString());
			} catch (Exception e) {

				// 可能找不到类或方法
				throw new ReflectException(cn, "parseAsConstructor", e);
			}
		} else {
			return (Constructor<?>) cn;
		}
	}

	public static char buildChar(Object charData) {
		Character result;
		if (charData instanceof String) {
			// 若为String类型，则获取字符串的第一个字符
			result = ((String) charData).charAt(0);
		} else if (charData instanceof FString) {
			// 若为kawa的FString类型，转换成String再执行本方法
			result = (char) buildChar(((FString) charData).toString());
		} else if (charData instanceof Integer) {
			result = (char) ((Integer) charData).intValue();
		} else if (charData instanceof Complex) {
			result = (char) ((Complex) charData).intValue();
		} else if (char.class.isInstance(charData)) {
			result = (char) charData;
		} else if (charData instanceof Character) {
			result = ((Character) charData).charValue();
		} else {
			throw new ReflectException(charData, "BuildChar", "构造char类型数据失败,类型不合法");
		}
		if (result != null) {
			Logger.log("BuildChar", "char数据构造成功,由数据", charData, "构造char数据成功", result);
		}
		return result;
	}

	/**
	 * 删除一个文件，或一个目录下的所有文件
	 * 
	 * @param file
	 *            一个文件对象或目录
	 */
	public static void deleteFile(File file) {
		// 只要file还存在就不断删除
		while (file.exists()) {
			if (file.isFile()) {
				// 如果是文件直接删除
				file.delete();
				Logger.log("Utils.deleteFile", "删除了文件");
			} else if (file.isDirectory()) {
				if (file.list().length == 0) {
					// 如果是空目录直接删除
					file.delete();
					Logger.log("Utils.deleteFile", "删除了文件夹", file);
				} else {
					// 如果是非空目录就遍历目录
					for (File file1 : file.listFiles()) {
						deleteFile(file1);
					}
				}
			}
		}
	}

}
